package com.tianji.learning.service.impl;

import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.po.PointsRecord;
import com.tianji.learning.domain.vo.PointsStatisticsVO;
import com.tianji.learning.enums.PointsRecordType;
import com.tianji.learning.mapper.PointsRecordMapper;
import com.tianji.learning.service.IPointsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 学习积分记录，每个月底清零 服务实现类
 * </p>
 *
 * @author hc
 * @since 2024-08-29
 */
@Service
public class PointsRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements IPointsRecordService {

    /**
     * 添加积分记录
     *
     * @param userId 积分人id
     * @param type   积分渠道
     * @param points 积分数
     */
    @Override
    public void savePointsRecord(Long userId, int type, Integer points) {
        //1、查询今日通过该渠道获取的积分数
        //SELECT SUM(points) AS points FROM `points_record` WHERE user_id = 2 and type = 1
        //and create_time BETWEEN "2023-02-14 22:19:11" and "2023-03-14 22:19:11"
        //1.1、获取今天的开始时间和结束时间
        LocalDateTime startTime = DateUtils.getDayStartTime(LocalDateTime.now());
        LocalDateTime endTime = DateUtils.getDayEndTime(LocalDateTime.now());

        PointsRecord pointsRecord = this.query()
                .select("SUM(points) AS points")
                .eq("user_id", userId)
                .eq("type", type)
                .between("create_time", startTime, endTime)
                .one();

        Integer counts = 0;
        if (ObjectUtils.isNotEmpty(pointsRecord) && ObjectUtils.isNotEmpty(pointsRecord.getPoints())) {
            counts = pointsRecord.getPoints();
        }

        //2、判断已获取积分是否超过上限
        PointsRecordType pointsRecordType = PointsRecordType.of(type);
        if (ObjectUtils.isEmpty(pointsRecordType)) {
            log.error("积分渠道类型传参异常");
            return;
        }
        int max = pointsRecordType.getMaxPoints();

        //2.1、该积分渠道有上限且已积分达到上限
        if (max != 0 && counts >= max) {
            log.error("今日该用户" + pointsRecordType.getDesc() + "渠道积分已达上限");
            return;
        }

        //3、判断此次积分加上今日累积是否超过上限
        if (max != 0 && counts + points > max) {
            //3.1、如果超过则这次记录添加积分为最大积分减去已积积分
            points = max - counts;
        }

        //4、添加积分记录
        this.save(new PointsRecord().setPoints(points).setType(type).setUserId(userId));


    }

    /**
     * 查询今日积分情况
     *
     * @return 今日积分列表
     */
    @Override
    public List<PointsStatisticsVO> getTodayPointsStatus() {
        //1、构建查询获取数据库今日已获取积分情况
        LocalDateTime startTime = DateUtils.getDayStartTime(LocalDateTime.now());
        LocalDateTime endTime = DateUtils.getDayEndTime(LocalDateTime.now());

        List<PointsRecord> list = this.query()
                .select("type , SUM(points) AS points")
                .eq("user_id", UserContext.getUser())
                .between("create_time", startTime, endTime)
                .groupBy("type")
                .list();
        //2、封装返回结果
        List<PointsStatisticsVO> vos = list.stream().map(p -> {
            PointsStatisticsVO vo = new PointsStatisticsVO();
            vo.setPoints(p.getPoints());
            PointsRecordType of = PointsRecordType.of(p.getType());
            vo.setMaxPoints(of.getMaxPoints());
            vo.setType(of.getDesc());
            return vo;
        }).collect(Collectors.toList());
        return vos;
    }
}
